<?php

include_once("ESSearch.php");
$service = new ESSearch("LTC");
$i=0;
$no_results=false;
function thumbnail($service,$URI,$local){
	$url = "thumbnails/".$local."-thumbnail.jpg";
	if(!file_exists($url)){
		$src_img = imagecreatefromjpeg("http://library.marist.edu".$URI);
		if($src_img){
			$old_x=imageSX($src_img);
			$old_y=imageSY($src_img);
			if ($old_x > $old_y) {
				$thumb_w=100;
				$thumb_h=$old_y*(100/$old_x);
			}
			if ($old_x < $old_y) {
				$thumb_w=$old_x*(100/$old_y);
				$thumb_h=100;
			}
			if ($old_x == $old_y) {
				$thumb_w=100;
				$thumb_h=100;
			}
			$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
			imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
			imagejpeg($dst_img, $url, 100);
			imagejpeg($dst_img, NULL, 100);
			exit;
		}
	}else {
		$img = imagecreatefromjpeg($url);
		imagejpeg($img, NULL, 100);
		exit;
	}
	print_r($_GET);
	exit;
	return false;
}
function html_headers_results($items){
	$mappings_text = array(
		"thumbnail" => "",
		"local_number" => "Local",
		"box_number" => "Box",
		"file_name" => "File",
		"index_number" => "Index",
		"date" => "Date",
		"size__inches_" => "Size",
		"title__description_" => "Title",
		"format" => "Links",
		//"research_cart" =>"Select", // Code to add checkbox column in exploro
	);
	$i=0;
	$mappings = array();
	foreach($mappings_text as $key => $value){
		$mappings[$key] = array( $value, $i);
		$i++;
	}
	$i=0;
	foreach($items as $item){
		$URIs[$i] = "/ESSearchApplication/".$item->documentURI;

		foreach($item->fields as $field){
			$myData[$i][$field->name] = $field->value;
		}
		$i++;
	}
?> </script>
	<script type="text/javascript">
		var data = new google.visualization.DataTable();
		var table = new google.visualization.Table();
		var dataSourceUrl = 'http://dev.library.marist.edu/ltc/ESSearchJSON.php';
		var query, container;
		var options = {'showRowNumber': true , 'allowHtml': true , 'page': 'event', 'pagingButtonsConfiguration': 'auto'};
		var gallery = new Array(<?php sizeof($myData) ?>);
<?php

			$i = $_POST['page']*$_POST['page_size'];
			if( $_POST['page'] > 0 ){
				echo 'data.addRows('.$i.')';
			}
			foreach($mappings as $a ) {
				echo '
			data.addColumn(\'string\', "'.$a[0].'");';
			}
			echo '
			data.addRows('.sizeof($myData).');';
			
			foreach($myData as $item ){
				foreach($item as $attr =>  $value ){
					// display thumbnail
					$mimetype = $myData[$i]["mimetype"];
					// PDF
					if (strpos($mimetype,'pdf') !== false) {
						echo 'data.setCell('.$i.', 0,' . '\'<a target="_blank" title="' . addslashes($myData[$i]["title__description_"]) .'" href="' . $URIs[$i] . '"><img src="thumbnails/adobe_pdf_icon.png" alt="PDF" /></a>' . '\');'; 
					}
					// image
					else {
						$path = "http://library.marist.edu/archives/search/thumbnails/" . $myData[$i]["local_number"] . "-thumbnail.jpg";
						//if (@fclose(@fopen($path, "r"))) {
							//echo 'data.setCell('.$i.', 0,' . '\'<a rel="prettyPhoto" name="'. addslashes($myData[$i]["link"]) . '"' . addslashes($myData[$i]["title__description_"]) . " "."(". addslashes($myData[$i]["file_name"])." "."-"." ".addslashes($myData[$i]["box_number"]).")".'" href="' . $URIs[$i] . '"><img src="?local=' . $myData[$i]["local_number"] . '&Thumbnail=' . urlencode($URIs[$i]) . '"></a>' . '\');'; 
								echo 'data.setCell('.$i.', 0,' . '\'<a rel="prettyPhoto" name="http://library.marist.edu/archives/LTP/Graphic%20Materials/Thomas2.1.1.2/airplanes2.1.1.2.2.xml"' . addslashes($myData[$i]["title__description_"]) . " "."(". addslashes($myData[$i]["file_name"])." "."-"." ".addslashes($myData[$i]["box_number"]).")".'" href="' . $URIs[$i] . '"><img src="?local=' . $myData[$i]["local_number"] . '&Thumbnail=' . urlencode($URIs[$i]) . '"></a>' . '\');'; 
								
						
						//}
					}
					
					// display data fields
					if( isset($mappings["$attr"][1] ) ){
						echo 'data.setCell('.$i.', '.$mappings["$attr"][1].',' . '\'<a style="color: #b31b1b; text-decoration: none;" ';
						// PDF
						if (strpos($mimetype,'pdf') !== false) {
							// open in new window
							echo 'target="_blank" ';
						}
						// image
						else {
							// display with slimbox2 image viewer
							//echo 'rel="lightbox" ';
							
							echo 'rel="prettyPhoto" name="http://library.marist.edu/archives/LTP/Graphic%20Materials/Thomas2.1.1.2/airplanes2.1.1.2.2.xml"';
							//echo 'rel="prettyPhoto" name="'. addslashes($myData[$i]["link"]) . '"';
							
							//echo 'rel="prettyPhoto['.addslashes($myData[$i]["title__description_"]).']" ';
						}
						echo 'title="' . addslashes($myData[$i]["title__description_"]) . " "."(". addslashes($myData[$i]["file_name"])." "."-"." ".addslashes($myData[$i]["box_number"]).")" . '" href="' . $URIs[$i] . '">' . addslashes($value) . '</a>' . '\');';
					}
					
					
					}
				
				/*
				// Code to add checkbox at the end of each loop
				echo 'data.setCell('.$i.',9 '.',' . '\'<input type="checkbox" class="innerCheckBox"   />' . '\');';
				*/
				
				echo '
			gallery['.$i.'] = [ "'.$URIs[$i].'", "('.$myData[$i]["local_number"].") ".$myData[$i]["title"].'" ];
			data.setRowProperty('.$i.', \'URI\', "'.($URIs[$i]).'");
					';
				$i++; 
				
			}
		?>

		function drawTable() { 
			table = new google.visualization.Table(document.getElementById('results'));
			for(var i=0;i<document.form1.page_size.length;i++){
				if(document.form1.page_size[i].checked){
					options['pageSize'] = (String)(document.form1.page_size[i].value);
				}

			}
			google.visualization.events.addListener(table, 'page', pageHandler);
			google.visualization.events.addListener(table, 'sort', sortHandler);
			
			// jQuter document ready event listener
			google.visualization.events.addListener(table, 'ready', function() {
				/*
				 jQuery(function($) {
					$("a[rel^='lightbox']").slimbox({// Put custom options here 
						}, null, function(el) {
						return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
					});
				});
				*/
			
				
			 
			jQuery(function($) {
				$("a[rel^='prettyPhoto']").prettyPhoto({
				theme: 'facebook'
			});
			
			
			// CODE  TO ATTACH RESEARCH CART IN EXOLORO
			/*	
			$('input.innerCheckBox').click(function(){
				alert(exploroResearchCart(this));
				//exploroResearchCart(this);
			});
			*/
			
		});
				
			});
			table.draw(data, options);
		}
		function sortHandler(event){
			data.sort([{column: event.column, desc: !event.ascending}]);
			var tmp = new Array(gallery.length);
			for(var i = 0; i < tmp.length;i++){
				tmp[i] = [data.getRowProperty(i, 'URI'), "("+data.getValue(i,0)+") "+data.getValue(i,6)]
			}
			gallery = tmp;
			options['sortColumn'] = event.column;
			options['sortAscending'] = event.ascending;
			table.draw(data,options);
			table.setSelection();
		}
		function thumbSelectHandler(id) {
			// jQuery.slimbox( gallery, id ); 
	jquery.prettyPhoto(gallery);
			}
		function pageHandler(e) { 
			document.form1.elements['page'].value = e['page'];
			document.form1.submit();
			return 0;
		}
		function drawDisplay(){
			drawTable();
		}
		function resizeTable(){
			if(document.form1.result_view[0].checked){
            drawThumbnails();
         }
		}
		$(window).bind('resize', resizeTable);
		google.setOnLoadCallback(drawDisplay);
<?php
}
function html_headers(){
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
	
		<title>Marist Archives Search</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<link rel="stylesheet" type="text/css" href="css/style.css" >
		<link rel="stylesheet" type="text/css" href="css/researchCart.css" >
		<link rel="stylesheet" href="css/slimbox2.css" type="text/css" media="screen" >
		
		<link rel="stylesheet" href="imageViewer/css/prettyPhoto.css" type="text/css" media="screen" >
		
		<script type="text/javascript">
			if (document.images) {
				homeOff = new Image
				homeOff.src = 'http://library.marist.edu/archives/images/homeOff.gif'
				maristOff = new Image
				maristOff.src = 'http://library.marist.edu/archives/images/maristOff.gif'
				libraryOff = new Image
				libraryOff.src = 'http://library.marist.edu/archives/images/libraryOff.gif'

				homeOn = new Image
				homeOn.src = 'http://library.marist.edu/archives/images/homeOn.gif'
				maristOn = new Image
				maristOn.src = 'http://library.marist.edu/archives/images/maristOn.gif'
				libraryOn = new Image
				libraryOn.src = 'http://library.marist.edu/archives/images/libraryOn.gif'
			}

			else {
				home = ""    ;  homeON = ""    ;  document.home = ""
				marist = ""   ;  maristON = ""   ;  document.marist = ""
				library = ""  ;  libraryON = ""  ;  document.library = ""
			}
		</script>
		<script type="text/javascript" src="http://www.google.com/jsapi"></script>
		<script type="text/javascript">
			google.load('visualization', '1', {packages: ['table']});
			google.load('jquery', '1');
			function compileSearchString() {
				return true;
			}
<?php
};
function html_body(){
?>

		</script>

		<script type="text/javascript" src= "https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
		<!--script src="js/researchCart.js" type="text/javascript" charset="utf-8"></script--><!-- jquery library of research cart -->
		<script type="text/javascript" src="js/jStorage.js"></script>
		<script src="imageViewer/js/jquery.prettyPhoto.js" type="text/javascript" charset="utf-8"></script><!-- jquery library of prettyphoto -->
		<!--script type="text/javascript" src="js/slimbox2.js"></script-->
	</head>
<body>
		<!-- ***** Main table begins here *****-->
<div id="bodyWrapper">
	<div id="headerContainer">
		<a href="http://library.marist.edu/archives/index.html"  target="_self">
		<div id="header"><div id="logo"></div></div>
		</a>
	</div>
	<div id="menu">
		<div id="menuItems">
		 	<a href= "http://library.marist.edu/archives/index.html" target="_self">Archives Home</a>
            <a href= "http://www.marist.edu" target="_blank">Marist Home</a>
            <a href="http://library.marist.edu/" target="_blank">Cannavino Library</a>
            <a href= "http://voyager.marist.edu/vwebv/searchBasic?sk=en_USmarist" target="_blank">Library Catalog</a>
		</div>
	</div><div id="contentWrapper"><div id="bodyContent">
		  <!-- ***** Side table ends here *****-->

		<!--***** CONTENT GOES HERE *****-->
		<h1 class="heading">Exploro Project - Jerin's Version</h1>

<?php
};
function html_footer(){
?>

</div></div></div>
	</body>
</html>

<?php
};
function html_form(){
?>

		<form method="post" name="form1" action="">
			<table style="text-align: right; margin-left: auto; margin-right: auto;">
			<input type="hidden" name="action" value="search" />
			<input type="hidden" name="page" value="0" />
			<tr><td>Keyword:</td><td> <input type="text" name="title" value="<?php if(isset($_POST["title"])) echo $_POST["title"]; else echo '"*"'; ?>" /><br /></td></tr>
			<br />
			<tr><td>Results Per Page:</td>
				<td>
					<input type="radio" <?php if(isset($_POST["result_view"])) echo 'onClick="drawDisplay();return 0;"';?> name="page_size" id="page_size" value="10" <?php if($_POST["page_size"] < "25") echo "checked";?> >10
					<input type="radio" <?php if(isset($_POST["result_view"])) echo 'onClick="drawDisplay();return 0;"';?> name="page_size" id="page_size" value="25" <?php if($_POST["page_size"] == "25") echo "checked";?> >25
					<input type="radio" <?php if(isset($_POST["result_view"])) echo 'onClick="drawDisplay();return 0;"';?> name="page_size" id="page_size" value="50" <?php if($_POST["page_size"] == "50") echo "checked";?> >50
					<input type="radio" <?php if(isset($_POST["result_view"])) echo 'onClick="drawDisplay();return 0;"';?> name="page_size" id="page_size" value="500" <?php if($_POST["page_size"] == "500") echo "checked";?> >All
				</td>
			</tr>

<tr><td colspan="2" style="text-align: center"><input type="submit" value="Search" onClick="compileSearchString();return 0" /></td></tr>
</table>
		</form>
	<div id="results"></div>
	
<?php
};
/*
 * No changes should need to be made
 * below this comment.
 *
 */
if(isset($_GET['URI']))
	$service->getItem($_GET["URI"]) and exit;
if(isset($_GET['Thumbnail']) && isset($_GET['local']))
	thumbnail($service, $_GET['Thumbnail'], $_GET['local'] ) and exit;
if(!isset($_POST["action"]) || !($_POST["action"] == "display") ){
	html_headers();
}
if(isset($_POST['action'])) {
	if ($_POST['action'] == "display" ){
		try{
			$service->getItem($_POST["URI"]) and exit;
		}
		catch( SoapFault $fault) {
         echo "REQUEST:\n" . $service->getLastRequest() . "\n";
         print("SOAP Fault: (faultcode: {$fault->faultcode}\n" .
            "faultstring: {$fault->faultstring})");
      }
	} else if($_POST['action']=="search") {
		try{
			
			$result = $service->search($_POST["title"], $_POST['page_size'], $_POST['page']);
			if($result->availableNumberOfResults >0){
				$items = $result->results;
				html_headers_results($items);
				
			}
			else {
				$no_results = TRUE;
			}
			html_body();
			
			$fieldsX= array();
			$fieldsX=$service->getFields();
			echo sizeof($fieldsX);
			print_r($fieldsX);
			
			if($no_results){
?>

		<h3 style="text-align: center;">No Results Found</h3>
		
<?php
			}
		} 
		catch( SoapFault $fault) {
			echo "REQUEST:\n" . $service->getLastRequest() . "\n";
			print("SOAP Fault: (faultcode: {$fault->faultcode}\n" .
				"faultstring: {$fault->faultstring})");
		}
	}
}else { 
	html_body();
}
html_form();
html_footer();
?>
